package com.retrofit.retrofitutil

import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

/**
 * 网络响应 callback 直接返回 Response的body
 * @param <M> 返回类型
</M> */
abstract class RetrofitCallback<M> : Callback<M> {
    /**
     * 网络响应
     */
    abstract fun onSuccess(model: M?)

    /**
     * 网络响应但错误
     */
    abstract fun onFailure(code: Int, msg: String?)

    /**
     * 异常、没响应
     */
    abstract fun onThrowable(t: Throwable)
    abstract fun onFinish()

    override fun onResponse(call: Call<M>, response: Response<M>) {
        if (response.isSuccessful) {
            onSuccess(response.body())
        } else {
            onFailure(response.code(), response.errorBody().toString())
        }
        onFinish()
    }

    override fun onFailure(call: Call<M>, t: Throwable) {
        if (call.isCanceled) {
            onFinish()
            // cancel
            //主动取消的请求 不计错误
        } else {
            // fail
            onThrowable(t)
        }
        onFinish()
    }
}